<!--
 * @Author: zxh
 * @Email: 1271027008@qq.com
 * @Date: 2020-05-25 11:07:08
 * @Descripttion: 
--> 
<template>
  <div class="app-container">
    <el-row>
      <h3>历史数据分析</h3>
    </el-row>
    <el-row style="margin-top: 20px;">
      <el-col :span="10">
        <span>用电总量：</span>
        <el-input
          type="text"
          @change="search"
          placeholder="请输入用电量Mwh"
          v-model="electricity"
          class="qxfx"
          style="width: 30%;margin-right:3px"
        ></el-input>
        <el-select
          v-model="checkedTimeList"
          multiple
          collapse-tags
          placeholder="请选择时间"
          clearable
          @change="selectAll"
          style="margin:0 3px 0 0"
        >
          <el-option v-for="item in timeList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <el-button type="primary" @click.native="search" class="theme_bg">生成曲线</el-button>
      </el-col>
      <el-col :span="14">
        <el-row type="flex">
          <el-col :span="24" style="text-align: right;padding-right: 40px;">
            <span style="cursor: pointer;" @click="goImport">
              已有
              <b class="theme_text">{{days}}</b>
              天数据
            </span>
            <el-button type="primary" size="small" @click="goImport" class="theme_bg">导入新数据</el-button>
            <el-button @click.native="exportClick" type="primary" size="small" class="theme_bg">一键导出</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row style="margin-top: 30px;">
      <el-col :span="6">
        <el-table :data="tableData" height="550" style="width: 98%">
          <el-table-column prop="time" label="时间"></el-table-column>
          <el-table-column prop="number1" label="平均用电量"></el-table-column>
          <el-table-column prop="number2" label="拆分后"></el-table-column>
        </el-table>
        <div class="total_line">
          <span>
            <b>合计</b>
          </span>
          <span>
            <b>{{sub1}}</b>
          </span>
          <span>
            <b>{{sub2}}</b>
          </span>
        </div>
      </el-col>
      <el-col :span="18">
        <div id="chart_box" style="width: 100%;height: 600px;"></div>
      </el-col>
    </el-row>
    <el-dialog title="数据源导入" :visible.sync="dialogTableVisible" width="30%">
      <el-row style="box-sizing: border-box;">
        <el-col :span="24">
          <span>
            已上传
            <b class="theme_text">{{totalModal}}</b> 份数据源
          </span>
          <el-upload
            style="display: inline;"
            class="upload-demo"
            :show-file-list="false"
            :action="baseUrl+'api/householdUploadData/upload'"
            :limit="1"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :headers="{ 'Authorization': infoPack.token}"
          >
            <el-button type="primary" size="mini" style="margin-left: 10px;" class="theme_bg">上传</el-button>
          </el-upload>
          <el-button
            @click="clearData"
            style="float: right;background-color:#fff;border-color:rgb(14, 125, 98);color: rgb(14, 125, 98);"
            type
            size="mini"
            class="theme_bg"
          >清空数据</el-button>
        </el-col>
        <el-col :span="24" style="margin-top:20px">
          <el-table :data="tableDataModal" height="400" style="width: 100%" border>
            <el-table-column prop="id" label="序号" width="80px"></el-table-column>
            <el-table-column label="文件名">
              <template slot-scope="scope">
                <a :href="scope.row.fileUrl" class="theme_text down_load">{{scope.row.fileName}}</a>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import config from '@/settings'
import echarts from 'echarts'
import axios from 'axios'

require('echarts/theme/macarons')
export default {
    data() {
        return {
            infoPack: null,
            baseUrl: config.apiUrl,
            electricity: "",
            days: 0,
            tableData: [],
            sub1: 0,
            sub2: 0,
            dialogTableVisible: false,
            tableDataModal: [],
            totalModal: 0,
            loadingInstance: null,
            checkedTimeList: [],
            oldCheckedTime: [],
            timeList: []
        }
    },
    created() {
        this.infoPack = this.$store.state.user
        axios.defaults.headers.common['Authorization'] = this.infoPack.token;
        this.getTimeList()
        this.getModalList()
    },
    methods:{
        getTimeList(){
          axios.get(this.baseUrl+'api/householdUploadData/dates',{})
            .then(res=>{
                let _newTimeList = ["全选"]
                _newTimeList = _newTimeList.concat((res.data).reverse())
                this.timeList = _newTimeList
                this.checkedTimeList = [_newTimeList[1]]
                this.getList('', 1)
            })
            .catch(error=>{
                console.log(error)
            })
        },
        selectAll(val){
            let allValues = []
            for(let item of this.timeList){
                allValues.push(item)
            }
            let oldVal = this.oldCheckedTime.length === 1 ? this.oldCheckedTime[0] : []
            // 若是全部选择
            if (val.includes('全选')) this.checkedTimeList = allValues
            // 取消全部选中 上次有 当前没有 表示取消全选
            if (oldVal.includes('全选') && !val.includes('全选')) this.checkedTimeList = []
            // 点击非全部选中 需要排除全部选中 以及 当前点击的选项
            // 新老数据都有全部选中
            if (oldVal.includes('全选') && val.includes('全选')){
                let index = val.indexOf('全选')
                val.splice(index, 1) // 排除全选选项
                this.checkedTimeList = val
            }
            // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
            if (!oldVal.includes('全选') && !val.includes('全选')){
                if (val.length === allValues.length - 1) this.checkedTimeList = ['全选'].concat(val)
            }
            // 储存当前最后的结果 作为下次的老数据
            this.oldCheckedTime[0] = this.checkedTimeList
        },
        getList(number, type) {
            let _num = ''
            if (number) {
                _num = number
            }
            if(this.checkedTimeList.includes('全选')){
                this.checkedTimeList.splice(0,1)
            }
            //let loadingInstance = this.$loading();
            axios.get(this.baseUrl + 'api/householdUploadData/avg?number='+_num+'&dates='+this.checkedTimeList, {
                headers:{
                  Authorization:this.infoPack.token,
                },
                params:{}
                })
                .then(res => {
                    this.tableData = res.data.list
                    this.days = res.data.days
                    this.sub1 = res.data.sumNumber1
                    this.sub2 = res.data.sumNumber2
                    let _xData = []
                    res.data.list.forEach(item=>{
                        _xData.push(item.time)
                    })
                    if (type == 1) {
                        let _newArr = []
                        res.data.list.forEach(item => {
                            _newArr.push(item.number1)
                        })
                        this.setOptions(_newArr,[],_xData)
                    }
                    if (type == 2) {
                        if (this.electricity == '') {
                            let _newArr3 = []
                            this.tableData.forEach(item => {
                                _newArr3.push(item.number1)
                            })
                            this.setOptions(_newArr3,[],_xData)
                        } else {
                            let _newArr1 = []
                            let _newArr2 = []
                            this.tableData.forEach(item => {
                                _newArr2.push(item.number1)
                                _newArr1.push(item.number2)
                            })
                            this.setOptions(_newArr2,_newArr1,_xData)
                        }
                    }
                    //loadingInstance.close();
                })
                .catch(err => {
                    loadingInstance.close();
                })
        },
        search() {
            if (this.electricity == '') {
                this.getList('', 2)
            } else {
                this.getList(this.electricity, 2)
            }
        },
        getModalList() {
            //this.loadingInstance = this.$loading();
            axios.get(this.baseUrl + 'api/householdUploadData/files', {
                headers:{
                  Authorization:this.infoPack.token,
                },
                params:{}
                })
                .then(res => {
                    let _newData = res.data
                    _newData.forEach(item => {
                        item.fileUrl = (this.baseUrl + item.fileUrl)
                    });
                    this.tableDataModal = _newData
                    this.totalModal = _newData.length
                    //this.loadingInstance.close();
                })
                .catch(err => {
                    console.log(err)
                    //this.loadingInstance.close();
                })
        },
        uploadSuccess(response, file, fileList) {
            this.$message.success('上传成功')
            this.getModalList()
            //this.loadingInstance.close();
        },
        beforeUpload() {
            //this.loadingInstance = this.$loading();
        },
        goImport() {
            this.dialogTableVisible = true
        },
        exportClick(){
            if(this.electricity.trim().length == 0){
                this.$message({
                    message: '请输入用电总量！',
                    type: 'warning'
                });
                return false
            }
            //window.location.href = this.baseUrl+"api/householdUploadData/download?number=" + this.electricity + '&dates=' + this.checkedTimeList

            let data = {number:this.electricity,dates: this.checkedTimeList }

            axios({
              url: this.baseUrl+"api/householdUploadData/download",
              method: 'get',
              responseType: 'blob',
              params: data  //与post传参方式不同之处
            }).then(res => {
              var blob = new Blob([res.data], 
              {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
              var filename = '曲线分析数据.xlsx';  
              var downloadElement = document.createElement('a');
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.style.display = 'none';
              downloadElement.href = href;
              downloadElement.download =filename ; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
              })
        },
        clearData(){
            axios.get(this.baseUrl+'api/householdUploadData/clear',{})
                .then(res=>{
                    this.getList()
                    this.getModalList()
                })
                .catch(err=>{
                    console.log(err)
                })
        },
        setOptions(num1, num2, xdata){
            let myChart = echarts.init(document.getElementById('chart_box'))
            myChart.setOption({
                title: {text: ''},
                tooltip: {
                    trigger: 'axis'
                },
                color:['rgb(14, 125, 98)','rgb(37,214,171)'],
                legend: {
                    data: ['平均值', '预测值']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {},
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xdata,
                    axisLabel: {  
                        interval:0,  
                        rotate:90  
                    } 
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '平均值',
                        type: 'line',
                        stack: '',
                        data: num1,
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: 'rgb(14,125,98)'
                                }
                            }
                        }            
                    },
                    {
                        name: '预测值',
                        type: 'line',
                        stack: '',
                        data: num2,
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: 'rgb(37,214,171)'
                                }
                            }
                        }
                    }
                ]
            })
        }
    }
};
</script>
<style>
.theme_bg,
.theme_bg:hover,
.theme_bg:focus,
.theme_bg:visited,
.theme_bg:active {
  background-color: rgb(14, 125, 98);
  border-color: rgb(14, 125, 98);
}
.theme_text {
  color: rgb(14, 125, 98);
}
.total_line {
  width: 98%;
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  box-shadow: 0 -5px 4px 2px rgba(119, 199, 180, 0.1);
  position: relative;
  z-index: 100;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  background-color: rgb(14, 125, 98);
}
.total_line span {
  display: inline-block;
  padding: 12px 0;
  font-size: 14px;
  color: #ffffff;
  width: 30.8%;
}
.total_line span b {
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #cedfdb;
}
.el-table__row td:last-child div {
  font-weight: bold;
}
.down_load {
  font-weight: normal;
  text-decoration: none;
}
.el-input__inner:focus {
  border-color: rgb(14, 125, 98);
}
.qxfx input{
  width: 100% !important;
}
</style>